﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace NyanBankIntfTool
{
    class IniParser
    {
        public string IniFileName { get; private set; }

        public Dictionary<string, Dictionary<string, string>> Ini { get; private set; }

        public IniParser()
        {
            Ini = new Dictionary<string, Dictionary<string, string>>();
        }

        public IniParser(string fileName)
        {
            IniFileName = fileName;

            Ini = new Dictionary<string, Dictionary<string, string>>();
            try
            {
                Read();
            }
            catch (FileNotFoundException)
            {
                CreateNew(IniFileName);
            }
        }

        public Dictionary<string, string> this[string tableName]
        {
            get => Ini[tableName];
        }

        public void Read()
        {
            ReadIniFile(IniFileName);
        }

        public void ReadIniFile(string fileName)
        {
            string line;

            StreamReader reader = new StreamReader(fileName);
            string curTableName = "";
            while ((line = reader.ReadLine()) != null)
            {
                Match match;
                if ((match = Regex.Match(line, @"^\[(.*)\]")).Success)
                {
                    GroupCollection groupCollection = match.Groups;
                    curTableName = groupCollection[1].Value;
                    Ini[curTableName] = new Dictionary<string, string>();
                }
                else if ((match = Regex.Match(line, @"^([^\[\];]*?)=([^\[\];]*)")).Success)
                {
                    GroupCollection groupCollection = match.Groups;
                    string key = groupCollection[1].Value;
                    string value = groupCollection[2].Value;
                    Ini[curTableName][key] = value;
                }
            }

            reader.Close();
        }

        public void CreateNew(string fileName)
        {
            FileStream file = new FileStream(fileName, FileMode.Create);
            file.Close();
        }

        public void AddTable(string tableName)
        {
            Ini[tableName] = new Dictionary<string, string>();
        }

        public void Save()
        {
            FileStream file = new FileStream(IniFileName, FileMode.Create);
            StreamWriter writer = new StreamWriter(file);
            foreach (var table in Ini)
            {
                writer.WriteLine($"[{table.Key}]");
                foreach (var row in table.Value)
                {
                    writer.WriteLine($"{row.Key}={row.Value}");
                }
            }

            writer.Close();
        }

        public string FindData(string table, string column)
        {
            string ret;
            Ini[table].TryGetValue(column, out ret);

            return ret;
        }
    }
}